package com.gt.lib.twitter;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.gt.common2.view.OhProgressDialog;

public class TwitterDialog extends Dialog {
	
	private final String TAG = "TwitterDialog";
	private final int MSG_TIMEOUT = 999;
	
	private Context mContext;
	
	private WebView mWebView;
	
	private OnAuthorizeSuccessListener mAuthorizeSuccessListener;
	
//	public ProgressDialog progressDialog;
	public OhProgressDialog progressDialog;
	
	private static int resIdDialogMessage=R.string.loading;
	
//	private String mCallbackUrl;
	private int mTimeout = 15;
	private OnTimeoutListener mTimeoutListener;
	private boolean isTimeout;
	private boolean isCancelTask;
	
	public TwitterDialog(Context context) {
		this(context, 0);
	}
	
	public TwitterDialog(Context context, int theme) {
		super(context, theme == 0 ? android.R.style.Theme_Translucent_NoTitleBar : theme);
		mContext = context;
				
		progressDialog = new OhProgressDialog(mContext);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setMessage(mContext.getString(resIdDialogMessage));
		progressDialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				isCancelTask = true;
				mTimeoutHandler.removeMessages(MSG_TIMEOUT);
			}
		});
	}
	
	public static int getResIdDialogMessage() {
		return resIdDialogMessage;
	}

	public static void setResIdDialogMessage(int resIdDialogMessage) {
		TwitterDialog.resIdDialogMessage = resIdDialogMessage;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initComponent();
		configWebView();
	}
	
	private void initComponent() {
		FrameLayout frameLayout = new FrameLayout(mContext);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		mWebView = new WebView(mContext);
		FrameLayout.LayoutParams webViewLP = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		ImageView closeButton = new ImageView(mContext);
		FrameLayout.LayoutParams buttonLP = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		
		//Set resources
        int closeDrawable = ResourceManager.getResource(ResourceManager.drawable_close, R.drawable.close);
		if(closeDrawable > 0) {
			closeButton.setImageDrawable(getContext().getResources().getDrawable(closeDrawable));
		}
		
        closeButton.setOnClickListener(new View.OnClickListener() { 
			
			@Override
			public void onClick(View v) {
				TwitterDialog.this.dismiss();
			}
		});
        
        int padding = closeButton.getDrawable().getIntrinsicWidth() / 2; 
        frameLayout.setPadding(padding, padding, padding, padding);
        frameLayout.addView(mWebView, webViewLP);
        
		int bgDrawable = ResourceManager.getResource(ResourceManager.drawable_dialogBackground, R.drawable.dialog_bg);
		
		
		if(bgDrawable > 0) {
			frameLayout.setBackgroundResource(bgDrawable);
		}
        
		setContentView(frameLayout, lp);
		addContentView(closeButton, buttonLP);

	}
	
	private void configWebView() {
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSaveFormData(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				showProgressDialog();
				super.onPageStarted(view, url, favicon);
			}
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, "Loading url: " + url);
				if(url.indexOf(oauth.signpost.OAuth.OAUTH_VERIFIER) > 0 && mAuthorizeSuccessListener != null) {
					mAuthorizeSuccessListener.onAuthorizeSuccess(url);
//					return false;
				}
//				else if(url.startsWith(mCallbackUrl)) {
//					dismiss();
//					return true;
//				}
				return true;
			}
			
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				dismiss();
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
//				if(url.indexOf(oauth.signpost.OAuth.OAUTH_VERIFIER) > 0 && mAuthorizeSuccessListener != null) {
//					mAuthorizeSuccessListener.onAuthorizeSuccess(url);
//				}
//				else if(url.startsWith(mCallbackUrl)) {
//					dismiss();
//				}
				dismissProgressDialog();
				Log.d(TAG, "onPageFinished: " + url);
				super.onPageFinished(view, url);
			}
        	
        });
        mWebView.setWebChromeClient(new WebChromeClient());
	}

//	public void setCallbackUrl(String url) {
//		mCallbackUrl = url;
//	}
	public void setTimeout(int timeout) {
		mTimeout = timeout;
	}
	
	public void showProgressDialog() {
		isTimeout = false;
		isCancelTask = false;
		dismissProgressDialog();
		progressDialog.show();
		mTimeoutHandler.removeMessages(MSG_TIMEOUT);
		mTimeoutHandler.sendEmptyMessageDelayed(MSG_TIMEOUT, mTimeout * 1000);
	}
	
	public void dismissProgressDialog() {
		if(progressDialog != null) {
			progressDialog.dismiss();
		}
		if(mWebView != null) {
			mWebView.bringToFront();
			mWebView.requestFocus();
		}
		mTimeoutHandler.removeMessages(MSG_TIMEOUT);
	}
	
	public void showLoginPage(String authorizationUrl) {
		show();
		mWebView.loadUrl(authorizationUrl);
	}
	
	public void setOnAuthorizeSuccessListener(OnAuthorizeSuccessListener l) {
		mAuthorizeSuccessListener = l;
	}
	
	public void setOnTimeoutListener(OnTimeoutListener l) {
		mTimeoutListener = l;
	}

	@Override
	public void dismiss() {
//		isCancelTask = true;
		if(mWebView != null) {
			mWebView.stopLoading();
		}
		dismissProgressDialog();
		super.dismiss();
	}
	
	private final Handler mTimeoutHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			isTimeout = true;
			removeMessages(MSG_TIMEOUT);
			dismiss();
			if(mTimeoutListener != null) {
				mTimeoutListener.onTimeout();
			}
			super.handleMessage(msg);
		}
	};

	public boolean isTimeout() {
		return isTimeout;
	}
	
	public boolean isCancelTask() {
		return isCancelTask;
	}
	
	public void setTypeface(Typeface tf) {
		if(progressDialog != null) {
			progressDialog.setTypeface(tf);
		}
	}
}
